package com.cyy.demo.controller;

import com.cyy.demo.common.BusinessException;
import com.cyy.demo.common.Result;
import com.cyy.demo.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    @RequestMapping("/upload")
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        String rootPath = System.getProperty(("user.dir"));//获取工作空间的根目录
        String timePath = LocalDate.now().toString();
        String fileName = file.getOriginalFilename();//获取文件名
        String uuid = UUID.randomUUID().toString();
//        String fullPath = String.format("%s/%s/%s_%s", rootPath, timePath, uuid,fileName);
        String fullPath = String.format("%s/%s/%s", rootPath, timePath,fileName);

        File newFile = new File(fullPath);
        if (!newFile.exists()) {
            try {
                newFile.getParentFile().mkdirs();
                newFile.createNewFile();
            }catch (IOException e){
                LOGGER.error("创建文件错误,{},{}",fullPath,e);
            }

        }

        file.transferTo(newFile);
        return new Result().toJson();
    }

    /**
     * 处理图片显示请求
     *
     * @param response
     */
    @RequestMapping("/show/{id}")
//    @ResponseBody
    public void showPicture(String id,HttpServletResponse response) {
        String fullPath = "E:/" + id + "." + "jpg";
        File imgFile = new File(fullPath);
        if (imgFile.exists()){
            responseFile(response, imgFile);
        }else{
            throw new BusinessException("图片不存在");
        }
    }

    /**
     * 处理图片下载请求
     *
     * @param fileName
     * @param response
     */
    @RequestMapping("/downloadPic/{fileName}.{suffix}")
    public void downloadPicture(@PathVariable("fileName") String fileName,
                                @PathVariable("suffix") String suffix,
                                HttpServletResponse response) {
        // 设置下载的响应头信息
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + "headPic.jpg");
        File imgFile = new File("E:/" + fileName + "." + suffix);
        responseFile(response, imgFile);
    }

    /**
     * 响应输出图片文件
     *
     * @param response
     * @param imgFile
     */
    private void responseFile(HttpServletResponse response, File imgFile) {
        try (InputStream is = new FileInputStream(imgFile);
             OutputStream os = response.getOutputStream();) {
            byte[] buffer = new byte[1024]; // 图片文件流缓存池
            while (is.read(buffer) != -1) {
                os.write(buffer);
            }
            os.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }


}
